<template>
  <div>
    <h1>购物车</h1>

    <fieldset>
      <legend>商品清单</legend>
      <el-table :data="cartlst">

        <el-table-column label="书名" prop="name">
        </el-table-column>

        <el-table-column label="作者" prop="author">
        </el-table-column>

        <el-table-column label="出版社" prop="house">
        </el-table-column>

        <el-table-column label="售价" prop="sellPrice">
          <template slot-scope="scope">
            {{ scope.row.sellPrice | price }}
          </template>
        </el-table-column>

        <el-table-column label="数量">
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              v-model="scope.row.cnt"
              :min="0"
              :max="Number(scope.row.stock)"
              @change="handleChange(scope)">
            </el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="删除">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
    </fieldset>
    <fieldset>
      <h3>总价：{{ sum | price }}</h3>
      <el-button class="submitbtn" @click="submit" type="primary" round>结算</el-button>
    </fieldset>
  </div>
</template>

<script>
import { int2price } from '@/utils/format'
import ShoppingCart from '@/utils/ShoppingCart'
import { CustomPostCart } from '@/utils/request'

export default {
  data () {
    return {
      cartlst: []
    }
  },
  computed: {
    sum () {
      let sum = 0
      for (let item of this.cartlst) {
        sum += item.cnt * item.sellPrice
      }
      return sum
    }
  },
  filters: {
    price (value) {
      return int2price(value, true)
    }
  },
  methods: {
    handleDelete (index, row) {
      ShoppingCart.remove(row)
      this.load()
    },
    handleChange (scope) {
      setTimeout(() => {
        ShoppingCart.set(scope.row, scope.row.cnt)
        this.load()
      }, 80)
    },
    submit () {
      const form = ShoppingCart.form()
      ShoppingCart.clear()
      CustomPostCart(form).then(rsp => {
        this.$notify({
          title: '已提交'
        })
        ShoppingCart.injectCookie(rsp.data)
        this.$router.push({
          name: 'MarketOrder'
        })
      })
    },
    load () {
      this.cartlst = Object.assign([], ShoppingCart.loadFromCookie())
    }
  },
  created () {
    this.load()
  }
}
</script>

<style lang="scss" scoped>
.el-form-item {
  margin: 0;
}
.submitbtn {
  float: right;
}
</style>
